package cn.icatw.leetcode.editor.cn;
//给定二叉树的根节点 root ，返回所有左叶子之和。
//
//
//
// 示例 1：
//
//
//
//
//输入: root = [3,9,20,null,null,15,7]
//输出: 24
//解释: 在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24
//
//
// 示例 2:
//
//
//输入: root = [1]
//输出: 0
//
//
//
//
// 提示:
//
//
// 节点数在 [1, 1000] 范围内
// -1000 <= Node.val <= 1000
//
//
//
//
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 724 👎 0


import java.util.Stack;

//Java：左叶子之和
public class T404_SumOfLeftLeaves {
    public static void main(String[] args) {
        Solution solution = new T404_SumOfLeftLeaves().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int sum = 0;
            // 如果左节点是叶子节点，那么加上左节点的值
         /*   if (isLeaf(root.left)) {
                sum += root.left.val;
            } else {
                // 如果左节点不是叶子节点，那么递归左节点
                sum += sumOfLeftLeaves(root.left);
            }
            // 递归右节点
            sum += sumOfLeftLeaves(root.right);*/
            //迭代法
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()) {
                TreeNode node = stack.pop();
                if (node.left!=null){
                    if (isLeaf(node.left)){
                        sum+=node.left.val;
                    }else {
                        stack.push(node.left);
                    }
                }
                if (node.right!=null){
                    stack.push(node.right);
                }
            }
            return sum;
        }

        private boolean isLeaf(TreeNode node) {
            return node != null && node.left == null && node.right == null;
        }
    }

    //leetcode submit region end(Prohibit modification and deletion)
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
